package com.umiwe.permission.service.impl;

import com.umiwe.utils.DingDingUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import com.umiwe.permission.service.DingDingService;
import com.umiwe.utils.DingDingUrlUtils;
import com.umiwe.utils.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class DingDingServiceImpl implements DingDingService {

    @Value("${dingtalk.Host}")
    private String host;

    @Value("${dingtalk.AppKey}")
    private String appKey;

    @Value("${dingtalk.Login.AppId}")
    private String loginAppId;

    @Value("${dingtalk.AppSecret}")
    private String appSecret;

    @Value("${dingtalk.Login.AppSecret}")
    private String loginAppSecret;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 获取钉钉授权 token
     */
    @Override
    public String getDingDingToken() {
        DingTalkClient client1 = new DefaultDingTalkClient(host+DingDingUrlUtils.GET_TOKEN.value());
        OapiGettokenRequest req1 = new OapiGettokenRequest();
        req1.setAppkey(appKey);
        req1.setAppsecret(appSecret);
        req1.setHttpMethod("GET");
        OapiGettokenResponse rsp = null;
        try {
            rsp = client1.execute(req1);
            redisUtil.set("dingToken", rsp.getAccessToken());
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return rsp.getAccessToken();
    }


    /**
     * 用户管理 单个
     * @param url
     * @param departmentId
     * @param offset
     * @param size
     * @return
     */
    @Override
    public OapiUserSimplelistResponse oapiUserSimplelistRequest(String url, Integer departmentId, Long offset, Long size) {
        OapiUserSimplelistResponse response = new OapiUserSimplelistResponse();
        String token = (String)redisUtil.get("dingToken");
        if(StringUtils.isBlank(token))
            token = this.getDingDingToken();
        DingTalkClient client = new DefaultDingTalkClient(host+url);
        OapiUserSimplelistRequest request = new OapiUserSimplelistRequest();
        request.setDepartmentId(Long.valueOf(departmentId));
        request.setOffset(offset);
        request.setSize(size);
        request.setHttpMethod("GET");
        try {
            response = client.execute(request, token);
            if(response.getErrcode() == 40014){
                token = this.getDingDingToken();
                response = client.execute(request, token);
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 用户管理 list
     */
    @Override
    public OapiUserListbypageResponse oapiUserListbypageRequest(String url, Integer departmentId, Long offset, Long size) {
        OapiUserListbypageResponse response = new OapiUserListbypageResponse();
        String token = (String)redisUtil.get("dingToken");
        if(StringUtils.isBlank(token))
            token = this.getDingDingToken();
        DingTalkClient client = new DefaultDingTalkClient(host+url);
        OapiUserListbypageRequest request = new OapiUserListbypageRequest();
        request.setDepartmentId(Long.valueOf(departmentId));
        request.setOffset(offset);
        request.setSize(size);
        request.setOrder("entry_desc");
        request.setHttpMethod("GET");
        try {
            response = client.execute(request, token);
            if(response.getErrcode() == 40014){
                token = this.getDingDingToken();
                response = client.execute(request, token);
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response;
    }


    /**
     * 部门管理
     * @param value
     * @param departmentId
     * @return
     */
    @Override
    public OapiDepartmentListResponse oapiDepartmentListRequest(String value, String departmentId) {
        OapiDepartmentListResponse response = new OapiDepartmentListResponse();
        String token = (String)redisUtil.get("dingToken");
        if(StringUtils.isBlank(token))
            token = this.getDingDingToken();
        DingTalkClient client = new DefaultDingTalkClient(host+value);
        OapiDepartmentListRequest request = new OapiDepartmentListRequest();
        if(departmentId.length() > 0){
            request.setId(departmentId);
        }
        request.setHttpMethod("GET");
        try {
            response = client.execute(request, token);
            if(response.getErrcode() == 40014){
                token = this.getDingDingToken();
                response = client.execute(request, token);
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 钉钉扫码 获取用户id
     */
    @Override
    public Map<String, String> oapiSnsGetuserinfoBycodeRequest(String code, String value) {
        String time = String.valueOf(new Date().getTime());
        Map map = new HashMap();
        String url = "?accessKey="+loginAppId+"&timestamp="+time+"&signature="+ DingDingUtils.signature(time,loginAppSecret);
        OapiSnsGetuserinfoBycodeResponse response  = new OapiSnsGetuserinfoBycodeResponse();
        DefaultDingTalkClient client = new DefaultDingTalkClient(host+value+url);
        OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest();
        req.setTmpAuthCode(code);
        req.setHttpMethod("POST");
        try {
            response = client.execute(req,loginAppId,loginAppSecret);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        map.put("code",response.getErrcode()+"");
        map.put("errmsg",response.getErrmsg());
        if(response.getErrcode() == 0L){
            map = this.oapiUserGetUseridByUnionidResponse(response);
        }
        return map;
    }

    /**
     * 根据unionid 获取userid
     * user/getUseridByUnionid
     */
    @Override
    public Map<String, String> oapiUserGetUseridByUnionidResponse(OapiSnsGetuserinfoBycodeResponse og) {
        Map map = new HashMap();
        OapiUserGetUseridByUnionidResponse response = new OapiUserGetUseridByUnionidResponse();
        String token = (String)redisUtil.get("dingToken");
        if(StringUtils.isBlank(token))
            token = this.getDingDingToken();
        DingTalkClient client = new DefaultDingTalkClient(host+ DingDingUrlUtils.USER_GETUSERID_BY_UNIONID.value());
        OapiUserGetUseridByUnionidRequest request = new OapiUserGetUseridByUnionidRequest();
        request.setUnionid(og.getUserInfo().getUnionid());
        request.setHttpMethod("GET");
        try {
            response = client.execute(request, token);
            if(response.getErrcode() == 40014){
                token = this.getDingDingToken();
                response = client.execute(request, token);
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        map.put("code",og.getErrcode()+"");
        map.put("errmsg",og.getErrmsg());
        map.put("openid",og.getUserInfo().getOpenid());
        map.put("unionid",og.getUserInfo().getUnionid());
        map.put("userid",response.getUserid());
        map.put("userName",og.getUserInfo().getNick());
        return map;
    }

    /**
     * 获取用户 详情信息
     * @param userId
     * @return
     */
    @Override
    public Map<String,String> userGet(String userId) {
        Map map = new HashMap();
        String token = (String)redisUtil.get("dingToken");
        if(StringUtils.isBlank(token))
            token = this.getDingDingToken();
        DingTalkClient client = new DefaultDingTalkClient(host+ DingDingUrlUtils.USER_GET.value());
        OapiUserGetRequest request = new OapiUserGetRequest();
        request.setUserid(userId);
        request.setHttpMethod("GET");
        OapiUserGetResponse response= new OapiUserGetResponse();
        try {
            response = client.execute(request, token);
            if(response.getErrcode() == 40014){
                token = this.getDingDingToken();
                response = client.execute(request, token);
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if(StringUtils.isNotBlank(response.getMobile()))
            map.put("mobile",response.getMobile());
        return map;
    }

    /**
     * liximing
     * @param methodName  方法名
     * @return
     */
    public String accessToken(String methodName){
       return this.getDingDingToken();
    }


}
